package com.example.demo.Gmail.imp;


import com.example.demo.Gmail.dao.MessageRepository;
import com.example.demo.Gmail.model.MessageModel;
import com.example.demo.Gmail.service.BackendService;
import com.google.common.collect.Lists;
import com.mongodb.WriteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("backendService")
@CacheConfig(cacheNames="Backend")
public class BackendServiceImp implements BackendService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    MessageRepository repository;

    /**
     * 批量插入数据
     * @param messageModels
     */
    @Override
    public void insertInbox(List<MessageModel> messageModels) {
        mongoTemplate.insert(messageModels,"mailInbox");
    }

    @Override
    public void insertSingleInbox(MessageModel messageModel) {
        mongoTemplate.insert(messageModel,"mailInbox");
    }

    /**
     * 异步处理发送邮件的数据添加到数据库，插入单条记录
     * @param messageModel
     */
    @Async
    @Override
    public void sentAndInsert( MessageModel messageModel) {
            mongoTemplate.insert(messageModel, "mailInbox");
        }

    /**
     * 查询指定邮箱，指定id
     * @param messageId
     * @return
     */
    @Override
    //@Cacheable(value = "getMessage", key = "#emailAddress+#messageId", unless = "#result eq null")
    public MessageModel getMessage(String messageId,String emailAddress) {
        Criteria criteria = Criteria.where("messageId").is(messageId).and("emailAddress").is(emailAddress);
        MessageModel result= mongoTemplate.findOne(new Query(criteria),MessageModel.class);
        return result;
    }


    /**
     * 查询指定邮箱类型所有数据
     * @return
     */
    @Override
   // @Cacheable(value = "messages", key = "#emailAddress", unless = "#result eq null")
    public List<MessageModel> messages(String lable,String emailAddress) {
        Criteria criteria = Criteria.where("label").is(lable).and("emailAddress").is(emailAddress);
        Query query=new Query(criteria);
       // query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "intnetdata")));
        List<MessageModel> messageModelList= mongoTemplate.find(query,MessageModel.class,"mailInbox");
        return messageModelList;
    }

    /**
     * 查询并更新
     * @param emailAddress
     * @param item
     * @param label
     * @return
     */
    @Override
   // @Cacheable(value = "labelMessages", key = "#emailAddress+#item", unless = "#result eq null")
    public List<MessageModel> labelMessages(String emailAddress,String item,String label) {
            List<MessageModel> messageModelList= Lists.newArrayList();
            Criteria criteria = Criteria.where("label").is(label).and("emailAddress").is(emailAddress);//.is(emailAddress).and("status").is(1);
            Query query=new Query(criteria);
            query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "intnetdata")));
            if (item!=null){
                query.limit(Integer.valueOf(item));
            }
            messageModelList= mongoTemplate.find(query,MessageModel.class,"mailInbox");
           /* if (messageModelList!=null){
              for (MessageModel messageModel:messageModelList){
                  this.Update(messageModel.getMessageId(),emailAddress);
              }
            }*/
        return messageModelList;
    }
    /**
     * 根据messageId删除单条记录
     * @param messageId
     */
    @Override
    public void delteMessage(String messageId) {
       Criteria criteria = Criteria.where("messageId").is(messageId);
       WriteResult result= mongoTemplate.remove(new Query(criteria),"mailInbox");

    }
    /**
     * 根据messageIds批量删除
     * @param messageIds
     */
    @Override
    public void batchDelteMessage(List<String> messageIds) {
        for (String messageId:messageIds){
            Criteria criteria = Criteria.where("messageId").is(messageId);
            mongoTemplate.remove(new Query(criteria),"mailInbox");
        }
    }

    @Override
    //@CachePut(value = "update", key = "#emailAddress+#messageId", unless = "#result eq null")
    public void Update(String messageId,String emailAddress) {
        Query query = new Query();
        query.addCriteria(Criteria.where("emailAddress").is(emailAddress).and("messageId").is(messageId));
        Update update = Update.update("status", 0);
        mongoTemplate.upsert(query,update,"mailInbox");

    }
    //分页查询
    @Override
    public Page<MessageModel> selectMessagePage(Integer currentPage, Integer pageSize, String emailAddress, String label) {
        Sort sort = new Sort(Sort.Direction.DESC, "intnetdata");
        Pageable page = new PageRequest(currentPage, pageSize, sort);
        Page<MessageModel> all=repository.findByEmailAddressAndLabel(emailAddress,label,page);
        return all;

    }
}
